package com.ruoyi.framework.config;

import java.util.Date;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * MyBatis Plus 审计字段自动填充处理器
 *
 * @author ruoyi
 */
@Component
public class AuditMetaObjectHandler implements MetaObjectHandler {

    private static final Logger log = LoggerFactory.getLogger(AuditMetaObjectHandler.class);

    /**
     * 插入时自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("开始插入填充...");

        // 获取当前登录用户
        LoginUser loginUser = getCurrentUser();
        String currentUserId = (loginUser != null) ? loginUser.getUserId() : "system"; // 如果未登录则使用默认值

        Date currentTime = new Date();

        // 自动填充创建信息
        this.strictInsertFill(metaObject, "createBy", String.class, currentUserId);
        this.strictInsertFill(metaObject, "createTime", Date.class, currentTime);
        this.strictInsertFill(metaObject, "updateBy", String.class, currentUserId);
        this.strictInsertFill(metaObject, "updateTime", Date.class, currentTime);

        log.debug("插入填充完成，用户: {}, 时间: {}", currentUserId, currentTime);
    }

    /**
     * 更新时自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("开始更新填充...");

        // 获取当前登录用户
        LoginUser loginUser = getCurrentUser();
        String currentUser = (loginUser != null) ? loginUser.getUserId() : "system"; // 如果未登录则使用默认值
        Date currentTime = new Date();

        // 自动填充更新信息
        this.strictUpdateFill(metaObject, "updateBy", String.class, currentUser);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, currentTime);

        log.debug("更新填充完成，用户: {}, 时间: {}", currentUser, currentTime);
    }

    /**
     * 获取当前登录用户
     */
    private LoginUser getCurrentUser() {
        try {
            return SecurityUtils.getLoginUser();
        } catch (Exception e) {
            log.warn("获取当前用户失败 ", e);
            return null;
        }
    }
} 